package com.example.demo.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreDome {
 class MyRunnable implements Runnable{

 	private Semaphore semaphore ;
 	private int user;

	 public MyRunnable(Semaphore semaphore, int user) {
		 this.semaphore = semaphore;
		 this.user = user;
	 }

	 @Override
	 public void run() {
		 try {
		 	//获取许可
			 semaphore.acquire();
			 System.out.println("用户"+this.user+"进入窗口，准备买票");
			 Thread.sleep((long)(Math.random()*10000));
			 System.out.println("用户"+this.user+"买票完成，即将离开");
			 Thread.sleep((long)(Math.random()*10000));
			 System.out.println("用户"+this.user+"离开售卖窗口");
			 //释放许可
			 semaphore.release();
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
	 }
 }

 public void task(){
	 final Semaphore semaphore = new Semaphore(2);
	 ExecutorService threadPool = Executors.newCachedThreadPool();
	 for (int i = 0; i < 20; i++) {
		 threadPool.execute(new MyRunnable(semaphore,i+1){});
	 }
	 threadPool.shutdown();
 }

	public static void main(String[] args) {
		SemaphoreDome semaphoreDome = new SemaphoreDome();
		semaphoreDome.task();

	}

}
